package com.xinzhidi.web.sim.controller;

import com.xinzhidi.common.annotation.Log;
import com.xinzhidi.common.core.controller.BaseController;
import com.xinzhidi.common.core.domain.AjaxResult;
import com.xinzhidi.common.core.domain.R;
import com.xinzhidi.common.core.page.TableDataInfo;
import com.xinzhidi.common.enums.BusinessType;
import com.xinzhidi.common.utils.poi.ExcelUtil;
import com.xinzhidi.web.sim.domain.dto.SimCardAddDto;
import com.xinzhidi.web.sim.domain.dto.SimCardListDto;
import com.xinzhidi.web.sim.domain.dto.SimCardUpdDto;
import com.xinzhidi.web.sim.domain.vo.SimCardInfoVo;
import com.xinzhidi.web.sim.domain.vo.SimCardListVo;
import com.xinzhidi.web.sim.service.ISimCardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * sim卡Controller
 *
 * @author ruoyi
 * @date 2023-05-25
 */
@RestController
@Api(tags = "sim卡")
@RequestMapping("/card")
public class SimCardController extends BaseController {
    @Autowired
    private ISimCardService simCardService;

    @ApiOperation("查询sim卡列表")
    @PreAuthorize("@ss.hasPermi('sim:card:list')")
    @PostMapping("/listSimCard")
    public TableDataInfo<SimCardListVo> listSimCard(@Validated @RequestBody SimCardListDto dto) {
        startPagePost(dto);
        return simCardService.selectSimCardList(dto);
    }

    @ApiOperation("导出sim卡列表")
    @PreAuthorize("@ss.hasPermi('sim:card:export')")
    @Log(title = "sim卡", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSimCard")
    public void exportSimCard(HttpServletResponse response, SimCardListDto dto) {
        TableDataInfo<SimCardListVo> list = simCardService.selectSimCardList(dto);
        ExcelUtil<SimCardListVo> util = new ExcelUtil<SimCardListVo>(SimCardListVo.class);
        util.exportExcel(response, list.getRows(), "sim卡数据");
    }

    @ApiOperation("获取sim卡详细信息")
    @PreAuthorize("@ss.hasPermi('sim:card:query')")
    @GetMapping(value = "/getSimCardById")
    public R<SimCardInfoVo> getSimCardById(@RequestParam("id") Long id) {
        return R.ok(simCardService.selectSimCardById(id));
    }

    @ApiOperation("新增sim卡")
    @PreAuthorize("@ss.hasPermi('sim:card:add')")
    @Log(title = "sim卡", businessType = BusinessType.INSERT)
    @PostMapping("addSimCard")
    public AjaxResult addSimCard(@Validated @RequestBody SimCardAddDto dto) {
        return toAjax(simCardService.insertSimCard(dto));
    }

    @ApiOperation("修改sim卡")
    @PreAuthorize("@ss.hasPermi('sim:card:edit')")
    @Log(title = "sim卡", businessType = BusinessType.UPDATE)
    @PostMapping("editSimCard")
    public AjaxResult editSimCard(@Validated @RequestBody SimCardUpdDto dto) {
        return toAjax(simCardService.updateSimCard(dto));
    }

    @ApiOperation("删除sim卡")
    @PreAuthorize("@ss.hasPermi('sim:card:remove')")
    @Log(title = "sim卡", businessType = BusinessType.DELETE)
    @DeleteMapping("/delSimCard")
    public AjaxResult delSimCard(@RequestParam Long[] ids) {
        return toAjax(simCardService.deleteSimCardByIds(ids));
    }

    /**
     * sim卡下载设备导入模板
     *
     * @throws Exception
     */
    @RequestMapping(value = "/downloadExcel")
    @ResponseBody
    public void downloadExcel(HttpServletResponse res, HttpServletRequest req) throws Exception {
        String name = "card";
        String fileName = name + ".xlsx";
        ServletOutputStream out;
        res.setContentType("multipart/form-data");
        res.setCharacterEncoding("UTF-8");
        res.setHeader("content-Type", "application/vnd.ms-excel");
        res.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        String filePath = getClass().getResource("/excelTemplate/" + fileName).getPath();
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
        }
        filePath = URLDecoder.decode(filePath, "UTF-8");

        res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        FileInputStream inputStream = new FileInputStream(filePath);
        out = res.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputStream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputStream.close();

        if (out != null) {
            out.flush();
            out.close();
        }

    }


    /**
     * sim卡导入
     *
     * @return com.xinzhidi.common.core.domain.AjaxResult
     * @author cx
     * @date 2023/5/25 11:13
     **/
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) {
        try {
            String result = simCardService.importExcel(file);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
